<template>
  <div class="mod-config">
    <div v-if="member">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()" ref="dataForm">
        <el-form-item>
          <el-input v-model="dataForm.name" placeholder="渠道名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.id" placeholder="请输入二维码ID"></el-input>
        </el-form-item>
        <el-form-item label="有效期：">
          <el-select v-model="dataForm.validDays" placeholder="请选择">
            <el-option
              v-for="item in [{label:'全部',value: null},...timerange]"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别：">
          <el-select v-model="dataForm.qrcodeType" placeholder="请选择">
            <el-option
              v-for="item in useroption1"
              :key="item.id"
              :label="item.channelName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search()">查询</el-button>
          <el-button type="primary" @click="addChannel()">添加渠道</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        style="width: 100%;"
      >
        <el-table-column prop="name" header-align="center" align="center" label="渠道名称"></el-table-column>
        <el-table-column header-align="center" align="center" label="有效期">
          <template slot-scope="scope">
            <span v-if="scope.row.validDays === -1">永久</span>
            <span v-else>{{scope.row.validDays}}天</span>
          </template>
        </el-table-column>
        <el-table-column prop="channelName" header-align="center" align="center" label="类别"></el-table-column>
        <el-table-column prop="id" header-align="center" align="center" label="二维码ID"></el-table-column>
        <el-table-column prop="gmtCreated" header-align="center" align="center" label="创建时间"></el-table-column>
        <el-table-column prop="gmtUpdate" header-align="center" align="center" label="修改时间"></el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" label="数据统计" width="150px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="statisticShow(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" label="操作" width="250px">
          <template slot-scope="scope">
            <el-button type="text" size="small"
                       v-clipboard:copy="scope.row.id"
                       v-clipboard:success="onCopy"
                       v-clipboard:error="onError"
            >复制ID
            </el-button>
            <el-button type="text" size="small" @click="showQrCode(scope.row.name, scope.row.qrcodeUrl)">生成二维码
            </el-button>
            <el-button type="text" size="small" @click="delThrow(scope.row)">删除</el-button>
            <el-button type="text" size="small" @click="addChannel(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>

      <!--添加投放s-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="visible1"
        title="添加渠道"
      >
        <el-form
          :model="dataForm1"
          ref="dataForm1"
          label-width="150px"
          :rules="rules"
        >
          <el-form-item label="渠道名称:" prop="name">
            <el-input v-model="dataForm1.name"></el-input>
          </el-form-item>
          <el-form-item label="有效期:" prop="validDays">
            <el-select v-model="dataForm1.validDays" placeholder="请选择">
              <el-option
                v-for="item in timerange"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <div class="flex" v-for="(item, index) in dataForm1.messageList">
            <div style="width: 100%;">
              <el-form-item
                :key="`${index}message`"
                :label="`消息JSON ${index + 1}`"
                :rules="[
            { required: true, message: '消息不能为空', trigger: 'blur' },
            { validator: JSONStringCheck, trigger: 'blur' }
          ]"
                :prop="'messageList.'+index+'.message'"
              >
                <el-input v-model="item.message" type="textarea" :rows="5" placeholder=""></el-input>
              </el-form-item>
              <el-form-item
                :key="`${index}immediatelyState`"
                :label="`推送时间 ${index + 1}`"
                :rules="[{ required: true, message: '推送时间不能为空', trigger: 'blur' }]"
                :prop="'messageList.'+index+'.immediatelyState'"
              >
                <el-radio-group v-model="item.immediatelyState">
                  <el-radio label="1">立即推送</el-radio>
                  <el-radio label="0">延时发送</el-radio>
                </el-radio-group>
                <div v-if="item.immediatelyState === '0'" style="display: inline-block;margin-left: 10px;">
                  <el-input v-model="item.hour" style="width:60px;"></el-input>
                  时
                  <el-input v-model="item.min" style="width:60px;"></el-input>
                  分
                  <el-input v-model="item.second" style="width:60px;"></el-input>
                  秒
                </div>
              </el-form-item>
            </div>
            <div class="del">
              <el-button type="danger" size="small" @click="delMessage(index)">删除</el-button>
            </div>
          </div>
          <el-form-item>
            <el-button type="primary" size="small" @click="addMessage">添加消息</el-button>
          </el-form-item>
          <el-form-item label="二维码类别:" prop="qrcodeType">
            <el-select v-model="dataForm1.qrcodeType" placeholder="请选择">
              <el-option v-for="item in appLabel" :key="item.id" :label="item.channelName"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible1 = false">取消</el-button>
          <el-button type="primary" @click="channelForm">确定</el-button>
        </span>
      </el-dialog>
      <!--添加渠道e-->

    </div>

    <!--数据统计-->
    <statistic-list v-else ref="statisticList" @goBack="goBack"></statistic-list>
  </div>
</template>

<script>
  import QRCode from "qrcode";
  import StatisticList from './throwStatisticList'

  export default {
    data() {
      return {
        messageList: [],
        member: true,
        isEdit: false,
        visibleIntegralList: false,
        dataForm: {
          channelType: null,
          channelName: ''
        },
        weCodeType: [
          {
            value: 1,
            label: '内部投放'
          },
          {
            value: 2,
            label: '外部投放'
          }
        ],
        dataForm1: {
          validDays: '',
          messageList: []
        },
        useroption1: [],
        rules: {
          name: [
            {required: true, message: '请输入渠道名称', trigger: 'blur'}
          ],
          validDays: [
            {required: true, message: '请选择有效天数', trigger: 'change'}
          ],
          qrcodeType: [
            {required: true, message: '请选择二维码类别', trigger: 'change'}
          ]
        },
        zanConfig: 0,
        visible1: false,
        dataList: [],
        dataListLoading: false,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        appLabel: [],
        useroption: [],
        timerange: [
          {
            label: '7天',
            value: 7
          },
          {
            label: '10天',
            value: 10
          },
          {
            label: '15天',
            value: 15
          },
          {
            label: '20天',
            value: 20
          },
          {
            label: '30天',
            value: 30
          },
          {
            label: '永久',
            value: -1
          }
        ],
        codeImg: '',
        visible2: false,
        dataForm2: {}
      }
    },
    components: {
      StatisticList
    },
    activated() {
      this.getAppLabel()
      this.getDataList()
      this.getForm()
    },
    methods: {
      search() {
        this.pageIndex = 1
        this.getDataList()
      },
      addMessage() {
        this.dataForm1.messageList.push({message: '', immediatelyState: '', second: 0, hour: 0, min: 0})
        this.dataForm1 = {...this.dataForm1}
      },
      delMessage(index) {
        this.dataForm1.messageList.splice(index, 1)
        this.dataForm1 = {...this.dataForm1}
      },
      JSONStringCheck(rule, value, callback) {
        if (!this.isJson(value)) {
          callback(new Error("请输入正确的json格式"));
        } else {
          callback();
        }
      },
      isJson(data) {
        if (typeof data === 'string') {
          try {
            var obj = JSON.parse(data)
            if (typeof obj === 'object' && obj) {
              return true
            } else {
              return false
            }
          } catch (e) {
            return false
          }
        }
      },
      showQrCode(adName, url) {
        var opts = {
          errorCorrectionLevel: "H",
          type: "image/jpeg",
          rendererOpts: {
            quality: 0.3
          }
        };
        QRCode.toDataURL(url, opts, (err, url) => {
          this.codeImg = url;
        });
        this.$alert(`<img style="width: 200px;" src="${this.codeImg}" />`, '生成二维码', {
          dangerouslyUseHTMLString: true,
          center: true,
          confirmButtonText: '保存二维码',
          callback: action => {
            if (action === 'confirm') {
              let a = document.createElement('a');
              let filename = `${adName}的二维码.png`;
              a.href = this.codeImg;
              a.download = filename;
              a.click();
            }
            // this.$message({
            //   type: 'info',
            //   message: `action: ${ action }`
            // });
          }
        });
      }
      ,
      onCopy() {
        this.$message({
          message: '复制成功',
          type: 'success'
        })
      }
      ,
      onError() {
        this.$message.error('复制失败');
      }
      ,
      edit(obj) {
        this.visible1 = true
        console.log(obj)
        this.dataForm1 = obj
        // this.dataForm2.id = obj.id
        // this.dataForm2.adName = obj.adName
        // this.dataForm2.surveyName = obj.surveyName
        // this.dataForm2.channelName = obj.channelName
        // this.dataForm2.remark = obj.remark
      }
      ,
      getAppLabel() {
        this.$http({
          url: this.$http.adornUrl('/market/marketchannel/channelNameList'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.appLabel = data.channelInfo
            this.useroption1 = [{id: null, channelName: '全部'}, ...data.channelInfo]
          }
        })
      }
      ,
      changeTime() {
        if (new Date(this.dataForm1.pushTime).getTime() < new Date().getTime()) {
          this.dataForm1.pushTime = ''
          this.$message.error('所选时间要大于当前时间')
        }
      }
      ,
      getForm() {
        this.$http({
          url: this.$http.adornUrl('/market/marketqrcode/list'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.useroption = data.list
          }
        })
      }
      ,
      statisticShow(id) {
        this.member = false
        this.$nextTick(() => {
          this.$refs.statisticList.init(id)
        })
      }
      ,
      goBack() {
        this.member = true
      }
      ,
      editChannelForm() {
        this.$refs['dataForm2'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl('/market/marketqrcode/save'),
              method: 'post',
              data: this.$http.adornData(this.dataForm2)
            }).then(({data}) => {
              if (data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible2 = false
                    this.getDataList()
                  }
                });
              } else {
                this.$message({
                  message: data.msg,
                  type: 'error',
                  duration: 1500,
                });
              }
            })
          }
        })
      }
      ,
      // 获取数据列表
      getDataList() {
        let basetUrl = 'http://yiban-api-test.qingclass.com/yiban-app/mpApi/landing/wx3596133503dd469e?redirectType=2&adHash='
        if (process.env.NODE_MYSELF) {
          basetUrl = 'https://yiban-c-api.ivykid.com/yiban-app/mpApi/landing/wxa1874f7d1d90e3ed?redirectType=2&adHash='
        }
        this.dataListLoading = true
        this.dataForm.page = this.pageIndex
        this.dataForm.limit = this.pageSize
        this.$http({
          url: this.$http.adornUrl('/market/marketqrcode/list'),
          method: 'get',
          params: this.$http.adornParams(this.dataForm)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$refs['dataForm'].resetFields()
            this.dataList = data.page.list
            const that = this
            data.page.list.map((item, index) => {
              that.dataList[index].redirectUrl = basetUrl + item.ticket
            })
            this.totalPage = data.page.totalCount
            console.log(this.dataList)
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      }
      ,
      addChannel(data) {
        this.visible1 = true
        this.$nextTick(() => {
          this.$refs['dataForm1'].resetFields()
          if (data) {
            this.dataForm1 = {...data}
            this.dataForm1.messageList = JSON.parse(this.dataForm1.message)
            this.dataForm1 = {...this.dataForm1}
          } else {
            this.dataForm1 = {
              validDays: '',
              messageList: []
            }
          }
          console.log(this.dataForm1)
        })
      }
      ,
      delThrow(id) {
        id.isAlive = 0;
        delete id.gmtCreated
        delete id.gmtUpdate
        this.$confirm('是否确定删除该条渠道二维码?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/market/marketqrcode/delete'),
            method: 'post',
            data: this.$http.adornData(id)
          }).then(({data}) => {
            if (data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              });
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {

        })
      }
      ,
      channelForm() {
        this.$refs['dataForm1'].validate((valid) => {
          if (valid) {
            delete this.dataForm1.gmtCreated
            delete this.dataForm1.gmtUpdate
            this.dataForm1.messageList.map((item, index) => {
              if (item.immediatelyState == 1) {
                this.dataForm1.messageList[index].latency = 0
              } else {
                this.dataForm1.messageList[index].latency = parseInt(item.hour * 60 * 60) + parseInt(item.min * 60) + parseInt(item.second)
              }
            })
            this.dataForm1.message = JSON.stringify(this.dataForm1.messageList)
            console.log(this.dataForm1)
            this.$http({
              url: this.$http.adornUrl(`/market/marketqrcode/${this.dataForm1.id ? 'update' : 'save'}`),
              method: 'post',
              data: this.$http.adornData(this.dataForm1)
            }).then(({data}) => {
              if (data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible1 = false
                    this.getDataList()
                  }
                });
              } else {
                this.$message({
                  message: data.msg,
                  type: 'error',
                  duration: 1500,
                });
              }
            })
          }
        })
      }
      ,
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      }
      ,
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      }
    }
  }
</script>
<style>
  .margin_10 {
    margin-bottom: 10px;
  }

  .text_r {
    text-align: right;
    padding-right: 15px;
  }

  .inineBlock {
    display: inline-block;
  }

  img {
    width: 100%;
    height: auto;
  }

  .flex {
    display: flex;
  }

  .del {
    flex: 1;
    margin-left: 20px;
  }
</style>
